#!/bin/bash

#=======================================================================
# konvflac
# File ID: dde2fab8-3dfd-11e0-9b12-1b57187fd9d3
# Convert .wav files to .flac and keep metadata
# License: GNU General Public License version 2 or later.
#=======================================================================

if test -z "$1"; then
    echo 'Syntax: konvflac wav_file [...]' >&2
    exit 1
fi
tmpuuid=$(suuid -m -t c_konvflac -wa -c "Starting conversion")
test -z "$tmpuuid" && { echo "konvflac: Broken suuid(1)" >&2; exit 1; }
chkfile="/tmp/konvflac.$tmpuuid.tmp"
for curr in "$@"; do
    echo
    echo ======== $(ls -l "$curr")
    rm -f "$chkfile"
    noext="$(basename "$curr" .wav)"
    wavfile="$noext.wav"
    flacfile="$noext.flac"
    test -e "$flacfile" && { echo $flacfile: File already exists >&2; continue; }
    wavsha=$(sha1sum "$wavfile" | cut -f1 -d ' ')
    wavid=$(finduuid "$wavfile")
    wavid_str=
    test -n "$wavid" && wavid_str=" (File ID $wavid)"
    # FIXME: Kludgy grep
    flac -T FILEID=$(suuid -m -t encode,c_konvflac -wa -c "Converting $wavfile$wavid_str to flac") --keep-foreign-metadata "$wavfile" 2>&1 | grep -v -e "keep-foreign-metadata is a new feature" -e "2000,2001,2002,2003,2004,2005,2006,2007" -e "2000-2009, 2011-2013" -e "flac comes with ABSOLUTELY NO WARRANTY" -e "welcome to redistribute it under certain conditions" -e '^$'
    flac -d -o "$chkfile" --keep-foreign-metadata "$flacfile" 2>&1 | grep -v -e "keep-foreign-metadata is a new feature" -e "2000,2001,2002,2003,2004,2005,2006,2007" -e "2000-2009, 2011-2013" -e "flac comes with ABSOLUTELY NO WARRANTY" -e "welcome to redistribute it under certain conditions" -e '^$'
    flacsha=$(sha1sum "$chkfile" | cut -f 1 -d ' ')
    if test "$wavsha" = "$flacsha"; then
        echo Verification OK
        rm -vf "$wavfile"
    else
        echo ==== ENCODING ERROR ====
        echo "$noext" >>konvflac-error.txt
    fi
done
